package iotwisp.school.user.entity;

import iotwisp.base.orm.StringIdBaseEntity;
import iotwisp.base.util.PwdUtil;
import iotwisp.base.util.UUIDGenerator;
import iotwisp.school.system.entity.Image;
import iotwisp.school.user.command.user.CreateUserSCmd;
import iotwisp.school.user.command.user.ModifyUserSCmd;
import iotwisp.school.wx.entity.WxUser;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Type;

import javax.persistence.*;
import java.util.Date;

@Data
@EqualsAndHashCode(callSuper = false)
@DynamicUpdate
@Entity
@Table(name = M.TABLE_PREFIX + "user")
@SuppressWarnings("serial")
public class User extends StringIdBaseEntity {

    /**
     * 名字
     */
    @Column(name = "name")
    private String name;

    /**
     * 电话
     */
    @Column(name = "mobile")
    private String mobile;

    /**
     * 登录密码
     */
    @Column(name = "password")
    private String password;

    /**
     * 头像照片
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "head_image_id", foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))
    private Image headImage;

    @Column(name = "reg_date", columnDefinition = M.DATE_COLUMN)
    private Date regDate;

    @Type(type = "yes_no")
    @Column(name = "enable")
    private Boolean enable;

    @Transient
    private WxUser wxUser;

    public void create(CreateUserSCmd cmd, Image headImage, User regReferrerUser) {

        setId(UUIDGenerator.getUUID());

        setName(cmd.getName());
        setMobile(cmd.getMobile());
        setPassword(PwdUtil.getPwd(cmd.getPassword()));
        setHeadImage(headImage);
        setRegDate(new Date());
        setEnable(true);
    }

    public void modify(ModifyUserSCmd cmd, Image headImage, User regReferrerUser) {

        setName(cmd.getName());
        setHeadImage(headImage);
        setMobile(cmd.getMobile());
        if (StringUtils.isNotBlank(cmd.getPassword())) {
            setPassword(PwdUtil.getPwd(cmd.getPassword()));
        }
    }

}
